package com.service.question.common.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author ：hjl
 * @date ：Created in 2022/03/10 17:11
 * @description：获取用户登录的ip地址
 */
public abstract class IpUtils {
    /**
     * 获取用户访问的ip
     * @param request
     * @return ip
     */
    public static String getRealIp(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (checkIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (checkIp(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (checkIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (checkIp(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (checkIp(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static String getIpByDomainName(String domainName)
    {
        InetAddress ip=null;

        try {
            ip = InetAddress.getByName(domainName);
        } catch (UnknownHostException e) {
            //非域名，返回ip地址
            return domainName;
        }

        return ip.getHostAddress();
    }

    public static  boolean checkIp(String ip)
    {
        return StringUtils.isEmpty(ip) || "unknow".equalsIgnoreCase(ip);
    }
}
